package com.example.demo1.aspect;


import com.example.demo1.annotation.Log;
import com.example.demo1.controller.TesterController;
import com.example.demo1.objects.ReturnObject1;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class LogAspect {
    private static final Logger log = LoggerFactory.getLogger(LogAspect.class);

    @Pointcut("@annotation(com.example.demo1.annotation.Log)")
    public void logPointcut(){

    }

    @Before("logPointcut()")
    public void beforePointCut(JoinPoint jp) {
        log.info("Lewis output before every log annotation");
        log.info(jp.getTarget().toString());
        log.info(jp.toString());
        log.info((jp.getArgs()[0]).toString());

        // how to get name Lewis of annotation Log
        Log lg = getAnnotationLog(jp);

        log.info(lg.name());
        log.info(String.valueOf(lg.age()));
        log.info(lg.gender());

    }

    @AfterReturning(pointcut="@annotation(com.example.demo1.annotation.Log)", returning = "str")
    public void afterRPointCut(JoinPoint jp, Object str)
    {
        log.info("Lewis output AfterReturning every log annotation");

        if (str instanceof ReturnObject1) {
            log.info(str.toString());
        }

    }

    /**
     * 是否存在注解，如果存在就获取
     */
    private Log getAnnotationLog(JoinPoint joinPoint)
    {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null)
        {
            return method.getAnnotation(Log.class);
        }
        return null;
    }
}
